﻿using System;
using System.Collections.Generic;
using System.Web;

namespace OF.Utility.WeixinPay
{
    public class NativePay
    {
        /**
        * 生成扫描支付模式一URL
        * @param productId 商品ID
        * @return 模式一URL
        */
        public string GetPrePayUrl(string productId)
        {
            Log.Info(this.GetType().ToString(), "Native pay mode 1 url is producing...");

            WxPayData data = new WxPayData();
            data.SetValue("appid", WxPayConfig.APPID);//公众帐号id
            data.SetValue("mch_id", WxPayConfig.MCHID);//商户号
            data.SetValue("time_stamp", WxPayApi.GenerateTimeStamp());//时间戳
            data.SetValue("nonce_str", WxPayApi.GenerateNonceStr());//随机字符串
            data.SetValue("product_id", productId);//商品ID
            data.SetValue("sign", data.MakeSign());//签名
            string str = ToUrlParams(data.GetValues());//转换为URL串
            string url = "weixin://wxpay/bizpayurl?" + str;

            Log.Info(this.GetType().ToString(), "Get native pay mode 1 url : " + url);
            return url;
        }

        /**
        * 生成直接支付url，支付url有效期为2小时,模式二
        * @param productId 商品ID
        * @return 模式二URL
        */
        public string GetPayUrl(string productId, string totalFee)
        {
            //  Log.Info(this.GetType().ToString(), "Native pay mode 2 url is producing...");
            //防止订单号重复，以原始订单号为基础构造一个虚拟个订单号，在回调时再还原为原始订单号
            var fakeOrderID = productId + "_" + DateTime.Now.ToString("MMddHHmmss");
            WxPayData data = new WxPayData();
            data.SetValue("body", WxPayConfig.PayBody);//商品描述
            data.SetValue("attach", WxPayConfig.Attach);//附加数据
            //data.SetValue("out_trade_no", productId);//随机字符串
             data.SetValue("out_trade_no", fakeOrderID);//随机字符串
            data.SetValue("total_fee", totalFee);//总金额
            data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));//交易起始时间
            data.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss"));//交易结束时间
            data.SetValue("goods_tag", "车务订单");//商品标记
            data.SetValue("trade_type", "NATIVE");//交易类型
            data.SetValue("product_id", productId);//商品ID
            data.SetValue("notify_url", "http://m.banmachewu.com/pay/wxNotify.aspx");//回掉地址

            WxPayData result = WxPayApi.UnifiedOrder(data);//调用统一下单接口
            string resultCode = result.GetValue("result_code").ToString();//SUCCESS FAIL
            string returnCode = result.GetValue("return_code").ToString();// SUCCESS FAIL
            if (returnCode == "SUCCESS" && resultCode == "SUCCESS")
            {
                return result.GetValue("code_url").ToString();//获得统一下单接口返回的二维码链接
            }
            if(resultCode == "FAIL")
            {
                return result.GetValue("err_code_des").ToString();
            }
            return "";
        }
        /// <summary>
        /// demo
        /// 
        /// </summary>
        /// <param name="productId"></param>
        /// <param name="totalFee"></param>
        /// <returns></returns>
        public string GetH5PayUrl(string productId, string totalFee)
        {
            try
            {
                //防止订单号重复，以原始订单号为基础构造一个虚拟个订单号，在回调时再还原为原始订单号
                var fakeOrderID = productId + "_" + DateTime.Now.ToString("MMddHHmmss");
                WxPayData data = new WxPayData();
                data.SetValue("body", WxPayConfig.PayBody);//商品描述
                data.SetValue("attach", WxPayConfig.Attach);//附加数据
                data.SetValue("out_trade_no", fakeOrderID);//随机字符串
                data.SetValue("total_fee", totalFee);//总金额
                data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));//交易起始时间
                data.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss"));//交易结束时间
                data.SetValue("goods_tag", "车务订单");//商品标记
                data.SetValue("trade_type", "MWEB");//交易类型
                data.SetValue("product_id", productId);//商品ID
                data.SetValue("notify_url", "http://m.banmachewu.com/pay/wxNotify2.aspx");//回调地址
               // data.SetValue("spbill_create_ip", IPHelper.IPAddress);//商品ID

                WxPayData result = WxPayApi.UnifiedOrder(data,6, IPHelper.IPAddress);//调用统一下单接口
                string resultCode = result.GetValue("result_code").ToString();//SUCCESS FAIL
                string returnCode = result.GetValue("return_code").ToString();// SUCCESS FAIL
                if (returnCode == "SUCCESS" && resultCode == "SUCCESS")
                {
                    //https://wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb?prepay_id=wx20170801095814bf42f3680a0187490895&package=1644136726
                    string url = result.GetValue("mweb_url").ToString();
                    if (!string.IsNullOrEmpty(url))
                    {
                        return url;
                    }
                }
                if (resultCode == "FAIL")
                {
                    return result.GetValue("err_code_des").ToString();
                }
            }
            catch (Exception e)
            {
                return e.Message;
            }
           
            return "";
        }
        /**
        * 参数数组转换为url格式
        * @param map 参数名与参数值的映射表
        * @return URL字符串
        */
        private string ToUrlParams(SortedDictionary<string, object> map)
        {
            string buff = "";
            foreach (KeyValuePair<string, object> pair in map)
            {
                buff += pair.Key + "=" + pair.Value + "&";
            }
            buff = buff.Trim('&');
            return buff;
        }
    }
}